package com.example.demo1

import com.example.util.p
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock


class Shop{

    @Volatile private var running = false


    var lock: Lock = ReentrantLock()

    private val goods = hashMapOf<Long,Int>()

    init{
        goods.put(1,10)
        goods.put(2,15)
    }

    @Synchronized fun buyGoods(id:Long){
        val stock = goods.getValue(id)
        goods.put(id,stock-1)
    }

    fun buyGoods2(id:Long){
        synchronized(this){
            val stock = goods.getValue(id)
            goods.put(id,stock-1)
        }
    }


    fun buyGoods3(id:Long){
        lock.lock()
        try {
            val stock = goods.getValue(id)
            goods.put(id,stock-1)
        }catch (ex:Exception){
            p("[Exception] is $ex")
        }finally {
            lock.unlock()
        }
    }

}



fun <T> withLock(lock: Lock,action:()->T):T{
    lock.lock()
    try {
        return action()
    }finally {
        lock.unlock()
    }
}

class Shop2(private var goods:HashMap<Long,Int>){
    private val lock:Lock = ReentrantLock()

    fun buyGoods(id:Long){
        lock.withLock {
            val stock = goods.getValue(id)
            goods.put(id,stock-1)
        }
    }


}


class ShopApi{
    private val A_goods = hashMapOf<Long,Int>()
    private val B_goods = hashMapOf<Long,Int>()

    private var shopA:Shop2
    private var shopB:Shop2

    init{
        A_goods.put(1,10)
        A_goods.put(2,15)

        B_goods[1] = 20
        B_goods[2] = 10

        shopA = Shop2(A_goods)
        shopB = Shop2(B_goods)




    }

    fun buyGoods(shopName: String,id:Long){
        when(shopName){
            "A" -> shopA.buyGoods(id)
            "B" -> shopB.buyGoods(id)
            else -> {}
        }
    }


}


fun main(){
    val shopApi = ShopApi()
    shopApi.buyGoods("A",1)
    shopApi.buyGoods("B",2)

}







